package com.dhx.dao.impl;

import com.dhx.dao.CompanyInfoDao;
import com.dhx.pojo.CompanyInfo;
import com.dhx.utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CompanyInfoDaoImpl implements CompanyInfoDao {
    @Override
    public int addInfo(CompanyInfo companyInfo) {
        String sql = "insert into t_companyinfo values (?,?,?,?,?)";
        Object[] objs = {companyInfo.getName(), companyInfo.getCno(), companyInfo.getArea(), companyInfo.getAno(), companyInfo.getDengji()};
        return DBUtil.excuteDML(sql, objs);
    }

    @Override
    public int deleteInfoById(String no) {
        String sql = "delete from t_companyinfo where cno=?";
        Object[] objs = {no};
        return DBUtil.excuteDML(sql, objs);
    }

    @Override
    public int updateInfo(CompanyInfo companyInfo) {
        String sql = "update t_companyinfo set name=?,area=?,ano=?,dengji=? where cno=?";
        Object[] objs = {companyInfo.getName(), companyInfo.getArea(), companyInfo.getAno(), companyInfo.getDengji(), companyInfo.getCno()};
        return DBUtil.excuteDML(sql, objs);
    }

    @Override
    public CompanyInfo queryInfoById(String no) {
        Connection conn = DBUtil.getConnection();
        String sql = "select * from t_companyinfo where cno=?";
        PreparedStatement ps = DBUtil.getPreparedStatement(conn, sql);
        try {
            ps.setString(1, no);
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        ResultSet rs = null;
        CompanyInfo companyInfo = null;
        try {
            rs = ps.executeQuery();
            if (rs.next()) {
                companyInfo = new CompanyInfo(rs.getString("name"), rs.getString("cno"), rs.getString("area"), rs.getString("ano"), rs.getString("dengji"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeAll(rs, ps, conn);
        }
        return companyInfo;
    }

    @Override
    public List<CompanyInfo> queryInfoes() {
        Connection conn = DBUtil.getConnection();
        String sql = "select * from t_companyinfo order by dengji DESC";
        PreparedStatement ps = DBUtil.getPreparedStatement(conn, sql);
        ResultSet rs = null;
        List<CompanyInfo> list = new ArrayList<CompanyInfo>();
        try {
            rs = ps.executeQuery();
            while (rs.next()) {
                CompanyInfo companyInfo = new CompanyInfo(rs.getString("name"), rs.getString("cno"), rs.getString("area"), rs.getString("ano"), rs.getString("dengji"));
                list.add(companyInfo);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeAll(rs, ps, conn);
        }
        return list;
    }
}
